<template>
    <div class="use-margin">
        <el-row>
            <el-col :span="12">
                <el-row>
                    <label for="fxAnswer">
                        <el-input
                            type="textarea"
                            :rows="10"
                            :disabled="showData"
                            placeholder="输入计算公式，例：(\${A} - \${1})/\${2}"
                            v-model="inputValue"
                            id="fxAnswer"
                            @blur="blur"
                        >
                        </el-input>
                    </label>
                </el-row>
            </el-col>
            <el-col :span="12" class="use-right">
                <el-row class="uer-operation">
                    <el-button @click="handelAddValue('+', '')" class="btn" :disabled="showData">+</el-button>
                    <el-button @click="handelAddValue('-', '')" class="btn" :disabled="showData">-</el-button>
                    <el-button @click="handelAddValue('*', '')" class="btn" :disabled="showData">*</el-button>
                    <el-button @click="handelAddValue('/', '')" class="btn" :disabled="showData">/</el-button>
                    <el-button @click="handelAddValue('()', '')" class="btn" :disabled="showData">()</el-button>
                    <el-button @click="handelAddValue('ABS()', '')" class="btn" :disabled="showData">ABS()</el-button>
                    <el-button @click="handelAddValue('MIN()', '')" class="btn" :disabled="showData">MIN()</el-button>
                    <el-button @click="handelAddValue('MAX()', '')" class="btn" :disabled="showData">MAX()</el-button>
                    <!-- v-show="showOtherBtn['6']" -->
                </el-row>
                <el-row class="right-add">
                    <p>
                        <span style="color:red;margin-right: 5px;">X</span>控制值
                        <el-button type="primary" icon="el-icon-plus" :disabled="showData" @click="handelAddValue('X', '控制值')" circle></el-button>
                    </p>
                    <p>
                        <span style="color:red;margin-right: 5px;">A</span>控制值1
                        <el-button type="primary" icon="el-icon-plus" :disabled="showData" @click="handelAddValue('A', '控制值1')" circle></el-button>
                    </p>
                    <p v-show="showthresholdType2">
                        <span style="color:red;margin-right: 5px;">B</span>控制值2
                        <el-button type="primary" icon="el-icon-plus" :disabled="showData" @click="handelAddValue('B', '控制值2')" circle></el-button>
                    </p>
                    <p v-show="showthresholdType3">
                        <span style="color:red;margin-right: 5px;">C</span>控制值3
                        <el-button type="primary" icon="el-icon-plus" :disabled="showData" @click="handelAddValue('C', '控制值3')" circle></el-button>
                    </p>
                    <p>
                        <span style="color:red;margin-right: 5px;">D</span>计算结果
                        <el-button
                            type="primary"
                            icon="el-icon-plus"
                            :disabled="showData"
                            @click="handelAddValue('D', '计算结果')"
                            circle
                        ></el-button>
                    </p>
                    <div v-for="itme in branchDataList" :key="itme.id">
                        <p>
                            <span style="color:red;margin-right: 5px;">{{ itme.id }}</span
                            >{{ itme.name }}
                            <el-button
                                type="primary"
                                icon="el-icon-plus"
                                :disabled="showData"
                                @click="handelAddValue(itme.id, itme.name)"
                                circle
                            ></el-button>
                        </p>
                    </div>
                </el-row>
                <el-row class="right-buts">
                    <el-col :span="4">
                        <el-button type="primary" :disabled="showData" @click="handelAddValue('simulation', '')">案例</el-button>
                    </el-col>
                    <el-col :span="4">
                        <el-button type="primary" :disabled="showData" @click="handelAddValue('verify', '')">校验</el-button>
                    </el-col>
                </el-row>
            </el-col>
            <el-col>
                <el-row>
                    <div class="input-data">
                        {{ inputValueTostring }}
                    </div>
                </el-row>
            </el-col>
        </el-row>
    </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskIconButton from '@/common/components/risk-icon-button.vue';

@Component({
    name: 'UseMargin',
    components: {
        RiskIconButton,
    },
})
/**
 * branchData:
 * entryControl:条目参数
 * riskEntryBranchs:分支详情
 * showData:是否禁用
 */
export default class UseMargin extends Vue {
    inputValue: any = '';
    @Prop() branchData!: any[];
    @Prop() entryControl!: any;
    @Prop() riskEntryBranchs!: any;
    @Prop() showData: boolean;
    branchDataList: any[] = [];
    branchAddList: any = {};
    entryControlList: any = {};
    riskEntryBranchsList: any[] = []; //  可操作分支点
    CountTypeChar = {
        '0': ' + ',
        '1': ' - ',
        '2': ' * ',
        '3': ' / ',
        '4': '||',
        '5': 'MIN()',
        '6': 'MAX()',
        // '7': '减去(日期)',
        // '8': '减去(交易日期)',
    };
    // eslint-disable-next-line no-template-curly-in-string
    inputValueTostring: any = '${控制值1} - ${分支1})/${分支2}';
    showthresholdType2: boolean = false;
    showthresholdType3: boolean = false;
    defaultData = [
        { id: 'X', name: '控制值' },
        { id: 'A', name: '控制值1' },
        { id: 'B', name: '控制值2' },
        { id: 'C', name: '控制值3' },
        { id: 'D', name: '计算结果' },
    ];
    // showOtherBtn = {
    //     '4': false,
    //     '5': false,
    //     '6': false,
    // };

    // 监听父组件动态传过来的值进行解析
    @Watch('branchData', { immediate: true, deep: true })
    async watchBranchData() {
        // console.log(this.branchData, 'this.branchData');
        // console.log(this.riskEntryBranchs, 'riskEntryBranchs');
        // this.showOtherBtn = {
        //     '4': false,
        //     '5': false,
        //     '6': false,
        // };
        // this.riskEntryBranchs.map(item => {
        //     let entryBranch = item.entryBranch;
        //     if (Object.keys(this.showOtherBtn).includes(entryBranch.countType)) {
        //         this.showOtherBtn[entryBranch.countType] = true;
        //     }
        // });
        let entryBranchCfg = JSON.parse(JSON.stringify(this.branchData));
        this.branchDataList = [];
        for (let i = 0; i < entryBranchCfg.length; i++) {
            if (entryBranchCfg[i].entryBranch.branchType === '0') {
                this.branchDataList.push({ id: String(entryBranchCfg[i].entryBranch.branchNo), name: entryBranchCfg[i].entryBranch.branchName });
            }
        }
    }

    // 条目明细字段改变
    @Watch('entryControl', { immediate: true, deep: true })
    watchusableSubstitute() {
        this.inputValue =
            this.entryControl.usableSubstitute ? this.entryControl.usableSubstitute
                .replace(/Math\.abs\(/, 'ABS(')
                .replace(/Math\.min\(/, 'MIN(')
                .replace(/Math\.max\(/, 'MAX(') : '';
        if (this.entryControl.thresholdType2) {
            this.showthresholdType2 = true;
        } else {
            this.showthresholdType2 = false;
        }

        if (this.entryControl.thresholdType3) {
            this.showthresholdType3 = true;
        } else {
            this.showthresholdType3 = false;
        }
    }

    //
    @Watch('riskEntryBranchs', { immediate: true, deep: true })
    watchriskEntryBranchs() {
        this.riskEntryBranchsList = this.riskEntryBranchs;
    }

    // 转换文字公式
    @Watch('inputValue', { deep: true })
    async watchInputValue() {
        let selectDataSource = [];
        selectDataSource.push(...this.branchDataList, ...this.defaultData);
        let inputValue = this.inputValue;

        if (inputValue) {
            let regex3 = /\$\{(.+?)\}/g;
            let fv = inputValue.match(regex3) || [];
            // todo
            let cv = inputValue.replace(regex3, '@@').split('@@') || [];
            let name = [];
            for (let i = 0; i < cv.length; i++) {
                name.push(cv[i]);
                if (fv[i]) {
                    let sn = selectDataSource.find(item => item.id === fv[i].substr(2, fv[i].length - 3)) || {};
                    name.push('${' + sn.name + '}');
                }
            }
            this.inputValueTostring = name.join('');
        } else {
            // eslint-disable-next-line no-template-curly-in-string
            this.inputValueTostring = '${控制值1} - ${分支1})/${分支2}';
        }
        // 回调函数
        this.setBranchData();
    }

    cursorIndex = 0;
    blur() {
        console.log(this.cursorIndex, 'cursorIndex');

        let fxAnswer: any = document.getElementById('fxAnswer');
        var cursorIndex = 0;
        if (document['selection']) {
            // IE Support
            fxAnswer.focus();
            var range = document['selection'].createRange();
            range.moveStart('character', -fxAnswer.value.length);
            cursorIndex = range.text.length;
        } else if (fxAnswer.selectionStart || fxAnswer.selectionStart === 0) {
            cursorIndex = fxAnswer.selectionStart;
        }
        this.cursorIndex = cursorIndex;
    }

    // 处理焦点
    focusPoint(index: number) {
        this.$nextTick(() => {
            let fxAnswer: any = document.getElementById('fxAnswer');
            fxAnswer.focus();
            fxAnswer.selectionStart = index;
            fxAnswer.selectionEnd = index;
        });
    }

    // 处理按钮点击
    handelAddValue(type: any, val: string) {
        let start = (this.inputValue || '').substr(0, this.cursorIndex);
        let end = (this.inputValue || '').substr(this.cursorIndex);
        console.log(start);
        console.log(start.length);

        if (['+', '-', '*', '/'].includes(type)) {
            this.inputValue = start + ' ' + type + ' ' + end;
            this.cursorIndex = this.cursorIndex + 3;
            this.focusPoint(start.length + 3);
        } else if (type == '()') {
            this.inputValue = start + '(  )' + end;
            this.cursorIndex = this.cursorIndex + 6;
            this.focusPoint(start.length + 2);
        } else if (type == 'ABS()') {
            this.inputValue = start + 'ABS(  )' + end;
            this.cursorIndex = this.cursorIndex + String(type).length;
            this.focusPoint(start.length + 5);
        } else if (type == 'MIN()') {
            this.inputValue = start + 'MIN(  )' + end;
            this.cursorIndex = this.cursorIndex + String(type).length;
            this.focusPoint(start.length + 5);
        } else if (type == 'MAX()') {
            this.inputValue = start + 'MAX(  )' + end;
            this.cursorIndex = this.cursorIndex + String(type).length;
            this.focusPoint(start.length + 5);
        } else if (type === 'simulation') {
            // 案例
            let returnValue = this.createSimulation();
            if (!returnValue) {
                this.yh_message_info('案例生成失败，请手动配置');
            } else {
                this.inputValue = returnValue;
            }
        } else if (type === 'verify') {
            // 校验
            this.handleVerify();
            return;
        } else {
            // 其他
            this.inputValue = start + '${' + type + '}' + end;
            this.cursorIndex = this.cursorIndex + String(type).length + 3;
            this.focusPoint(this.inputValue.length - end.length);
        }
        this.setBranchData();
    }

    // 回调函数
    setBranchData() {
        this.$emit(
            'set-use-data',
            this.inputValue
            // .replace(/ABS\(/, 'Math.abs(')
            // .replace(/MIN\(/, 'Math.min(')
            // .replace(/MAX\(/, 'Math.max(') || ''
        );
    }

    //  案例
    createSimulation() {
        let entryControl = this.entryControl;
        let entryBranchCfg = this.riskEntryBranchsList || [];
        if (entryBranchCfg.length === 0) {
            return null;
        }
        // 获取最高级别的阀值
        let tt = 'A';
        let maxTT = '0';
        for (let i = 1; i <= 3; i++) {
            if (!entryControl['thresholdType' + i]) {
                continue;
            }
            // 获取最大的阈值和序号
            if (Number(entryControl['thresholdType' + i]) > Number(maxTT)) {
                maxTT = entryControl['thresholdType' + i];
                tt = { '1': 'A', '2': 'B', '3': 'C' }[String(i)];
            }
        }
        // 确认主分支
        let il = entryBranchCfg.filter(item => item.entryBranch.parentBranchNo === 0);
        if (il.length === 2 && il[0].entryBranch.countType !== '3' && il[1].entryBranch.countType === '3') {
            // eslint-disable-next-line
            let returnValue = ' ( ${' + tt + '} - ${D} ) * ';
            if (il[1].entryBranch.branchType === '0') {
                // 子节点
                returnValue = returnValue + ' ${' + il[1].entryBranch.branchNo + '}';
            } else {
                // 组节点
                returnValue = returnValue + this.findGroupChildren(entryBranchCfg, il[1].entryBranch.branchNo);
            }
            return returnValue;
        } else {
            // eslint-disable-next-line
            return '${' + tt + '} - ${D}';
        }
    }

    // 组节点处理
    findGroupChildren(entryBranchCfg: any, parentBranchNo: any) {
        let formula = '( ';
        let index = 0;
        for (let vaue of entryBranchCfg) {
            if (vaue.entryBranch.parentBranchNo === parentBranchNo) {
                if (index > 0) {
                    formula = formula + this.CountTypeChar[vaue.entryBranch.countType];
                }
                if (vaue.entryBranch.branchType === '0') {
                    formula = formula + '${' + vaue.entryBranch.branchNo + '}';
                } else {
                    formula = formula + this.findGroupChildren(entryBranchCfg, vaue.entryBranch.branchNo);
                }
                index = index + 1;
            }
        }
        formula = formula + ' ) ';
        return formula;
    }

    // 校验
    handleVerify() {
        let selectDataSource = [];
        selectDataSource.push(...this.branchDataList, ...this.defaultData);
        let inputValue = this.inputValue;
        // if (this.showOtherBtn['4']) {
        // 绝对值
        inputValue = inputValue.replace(/ABS\(/, '(') || '';
        // }
        // if (this.showOtherBtn['5']) {
        // 取负
        inputValue = inputValue.replace(/MIN\(/, '(').replace(/,0\)/g, ')') || '';
        // }
        // if (this.showOtherBtn['6']) {
        inputValue = inputValue.replace(/MAX\(/, '(').replace(/,0\)/g, ')') || '';
        // }

        let regex3 = /\$\{(.+?)\}/g;
        let fv = inputValue.match(regex3) || [];
        let cv = inputValue.replace(regex3, '@@').split('@@') || [];
        let name = '';

        for (let i = 0; i < cv.length; i++) {
            name += cv[i];
            if (fv[i]) {
                let sn = selectDataSource.find(item => item.id === fv[i].substr(2, fv[i].length - 3)) || {};
                if (sn.name) {
                    name += ' 1 ';
                }
            }
        }
        if (name.length <= 1 || name.trim().length <= 1) {
            this.yh_message_warn('配置公式不正确，请检查');
            return;
        }

        // if (this.showOtherBtn['4']) {
        //     // 移除绝对值
        //     name = name.replace(/\|/g, '');
        // }

        let regp = /[^0-9+\-*/() ]/;

        if (name.match(regp) !== null) {
            this.yh_message_warn('配置公式不正确，请检查');
            return;
        }
        try {
            // eval 并不是仅仅作为解析字符串用。。更多的是执行动态代码上面，例如把字符串作为代码执行
            let value = eval('let result = ' + name); // eslint-disable-line
            console.log(value, 'eval-value');
            this.yh_message_success('配置正确');
        } catch (e) {
            this.yh_message_warn('配置公式不正确，请检查');
        }
    }
}
</script>
<style lang="scss" scoped>
.use-margin {
    color: #222;

    .use-right {
        height: 218px;
        // width: 100%;
        border: 1px solid #eee;

        .uer-operation {
            border-bottom: 1px solid #eee;
            padding: 2px;
            .btn {
                background-color: #e6f7ff;
            }
        }

        .uer-operation /deep/ .el-button {
            padding: 4px 0px;
        }

        .right-add {
            height: 120px;
            overflow: auto;
            margin-top: 10px;
            padding-left: 5px;
        }

        .right-add /deep/ .el-button.is-circle {
            padding: 2px;
        }

        .right-buts {
            border-top: 1px solid #eee;
            margin-top: 10px;
            padding-top: 10px;
            padding-left: 5px;
        }
    }

    .input-data {
        height: 32px;
        border: 1px solid #eee;
        margin-top: 5px;
        line-height: 32px;
    }
}
</style>
